package com.github.lazylibrary.util;

import android.text.TextUtils;
import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用来计算显示的时间是多久之前的！
 */
public class TransitionTime {

    private Date endDate;
    private static SimpleDateFormat formatBuilder;
    public static final int WEEKDAYS = 7;
    public static String[] WEEK = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };

    public TransitionTime(long endTime) {
        endDate = new Date(endTime);
    }


    public long timeMills = 0;


    /**
     * 时间转换
     *
     * @param time    时间
     * @param timeFormat 时间的格式 eg: yyyy-MM-dd hh:mm:ss
     * @return  String
     */
    public String convert(String time, String timeFormat) {

        timeMills = Long.parseLong(time);
        Date date = new Date(timeMills);
        String strs = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
            strs = sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strs;
    }


    /**
     *
     * @param startTime  开始的事件
     * @return  返回距离发帖时间的时间差
     */
    public String twoDateDistance(String startTime) {

        if (startTime.equals("")) {

            return "";
        }
        timeMills = Long.parseLong(startTime);
        Date startDate = new Date(timeMills);

        if (startDate == null || endDate == null) {
            return null;
        }
        long timeLong = endDate.getTime() - startDate.getTime();
        if (timeLong <= 0) {
            return "刚刚";
        }
        else if (timeLong < 60 * 1000) {
            return timeLong / 1000 + "秒前";
        }
        else if (timeLong < 60 * 60 * 1000) {
            timeLong = timeLong / 1000 / 60;
            return timeLong + "分钟前";
        }
        else if (timeLong < 60 * 60 * 24 * 1000) {
            timeLong = timeLong / 60 / 60 / 1000;
            return timeLong + "小时前";
        }
        else if (timeLong < 60 * 60 * 24 * 1000 * 7) {
            timeLong = timeLong / 1000 / 60 / 60 / 24;
            return timeLong + "天前";
        }
        else if (timeLong < 60 * 60 * 24 * 1000 * 7 * 4) {
            timeLong = timeLong / 1000 / 60 / 60 / 24 / 7;
            return timeLong + "周前";
        }
        else {
            timeLong = timeLong / 1000 / 60 / 60 / 24;
            return timeLong + "天前";
        }
    }

    /**
     * UTM转换成日期描述，如三周前，上午，昨天等
     *
     * @param milliseconds milliseconds
     * @param isShowWeek 是否采用周的形式显示  true 显示为3周前，false 则显示为时间格式mm-dd
     * @return  如三周前，上午，昨天等
     */

    public static String getTimeDesc(long milliseconds,boolean isShowWeek) {
        StringBuffer sb = new StringBuffer();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        long hour = calendar.get(Calendar.HOUR_OF_DAY);

        calendar.setTimeInMillis(System.currentTimeMillis());
        long hourNow = calendar.get(Calendar.HOUR_OF_DAY);

        Log.v("---------->---", System.currentTimeMillis() + "----------"+ milliseconds);
        long datetime = System.currentTimeMillis() - (milliseconds);
        long day = (long) Math.floor(datetime / 24 / 60 / 60 / 1000.0f) + (hourNow<hour?1:0);// 天前

        if (day <= 7) {// 一周内
            if (day == 0) {// 今天
                if(hour <=4){
                    sb.append(" 凌晨 ");
                }else if(hour >4 && hour <=6){
                    sb.append(" 早上 ");
                }else if(hour >6 && hour <=11){
                    sb.append(" 上午 ");
                }else if(hour >11 && hour <=13){
                    sb.append(" 中午 ");
                }else if(hour >13 && hour <=18){
                    sb.append(" 下午 ");
                }else if(hour >18 && hour <=19){
                    sb.append(" 傍晚 ");
                }else if(hour >19 && hour <=24){
                    sb.append(" 晚上 ");
                }else{
                    sb.append("今天 ");
                }
            } else if (day == 1) {// 昨天
                sb.append(" 昨天 ");
            } else if (day == 2) {// 前天
                sb.append(" 前天 ");
            } else {
                sb.append(" " + DateToWeek(milliseconds) +" ");
            }
        } else {// 一周之前
            if(isShowWeek){
                sb.append((day%7==0?(day/7):(day/7+1)) + "周前");
            }else{
                formatBuilder = new SimpleDateFormat("MM-dd");
                String time = formatBuilder.format(milliseconds);
                sb.append(time);
            }
        }
        Log.v("sb---", sb.toString() + "");
        return sb.toString();

    }

    /**
     * UTM转换成日期描述，如三周前，上午，昨天等
     *
     * @param milliseconds    时间
     * @return UTM转换成日期描述，如三周前，上午，昨天等
     * */
    public static String getTimeDesc(long milliseconds) {

        return getTimeDesc(milliseconds,true);
    }

    /**
     * UTM转换成日期 ,hh:mm
     *
     * @param milliseconds  milliseconds
     * @return UTM转换成日期 ,hh:mm
     */

    public static String getDisplayTime(long milliseconds) {
        formatBuilder = new SimpleDateFormat("HH:mm");
        String time = formatBuilder.format(milliseconds);
        return time;
    }

    /**
     * UTM转换成带描述的日期
     *
     * @param milliseconds  milliseconds
     * @return   UTM转换成带描述的日期
     */

    public static String getDisplayTimeAndDesc(long milliseconds) {
        formatBuilder = new SimpleDateFormat("HH:mm");
        String time = formatBuilder.format(milliseconds);
        StringBuffer sb = new StringBuffer();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        long hour = calendar.get(Calendar.HOUR_OF_DAY);
        Log.v("---------->---", System.currentTimeMillis() + "----------"+ milliseconds);
        long datetime = System.currentTimeMillis() - (milliseconds);
        long day = (long) Math.ceil(datetime / 24 / 60 / 60 / 1000.0f);// 天前
        Log.v("day---hour---time---", day + "----" + hour + "-----" + time);

        if (day <= 7) {// 一周内
            if (day == 0) {// 今天
                if(hour <=4){
                    sb.append(" 凌晨 " + time);
                }else if(hour >4 && hour <=6){
                    sb.append(" 早上 " + time);
                }else if(hour >6 && hour <=11){
                    sb.append(" 上午 " + time);
                }else if(hour >11 && hour <=13){
                    sb.append(" 中午 " + time);
                }else if(hour >13 && hour <=18){
                    sb.append(" 下午 " + time);
                }else if(hour >18 && hour <=19){
                    sb.append(" 傍晚 " + time);
                }else if(hour >19 && hour <=24){
                    sb.append(" 晚上 " + time);
                }else{
                    sb.append("今天 " + time);
                }
            } else if (day == 1) {// 昨天
                sb.append("昨天 " + time);
            } else if (day == 2) {// 前天
                sb.append("前天 " + time);
            } else {
                sb.append(DateToWeek(milliseconds) + time);
            }
        } else {// 一周之前
            sb.append(day % 7 + "周前");
        }
        Log.v("sb---", sb.toString() + "");
        return sb.toString();

    }

    /**
     * 日期变量转成对应的星期字符串
     *
     * @param milliseconds    data
     * @return  日期变量转成对应的星期字符串
     */
    public static String DateToWeek(long milliseconds) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        int dayIndex = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayIndex < 1 || dayIndex > WEEKDAYS) {
            return null;
        }

        return WEEK[dayIndex - 1];
    }

    /**
     * 将时间间隔转换成描述性字符串，如2天前，3月1天后等。
     * @param toDate 相对的日期
     * @param isFull 是否全部显示 true 全部显示 false 简单显示
     * @return  将时间间隔转换成描述性字符串，如2天前，3月1天后等。
     */
    public static String diffDateAsDesc(Date toDate, boolean isFull) {
        String diffDesc = "";
        String fix = "";
        Long diffTime;
        Date curDate = new Date();
        if(curDate.getTime() > toDate.getTime()) {
            diffTime = curDate.getTime() - toDate.getTime();
            fix = "前";
        } else {
            diffTime = toDate.getTime() - curDate.getTime();
            fix = "后";
        }

        //换算成分钟数，防止Int溢出。
        diffTime = diffTime/1000/60;

        Long year = diffTime/(60 * 24 * 30 * 12);
        diffTime = diffTime % (60 * 24 * 30 * 12);
        if(year > 0) {
            diffDesc = diffDesc + year + "年";
            if(!isFull) {
                return diffDesc + fix;
            }
        }

        Long month = diffTime/(60 * 24 * 30);
        diffTime = diffTime % (60 * 24 * 30);
        if(month > 0) {
            diffDesc = diffDesc + month + "月";
            if(!isFull) {
                return diffDesc + fix;
            }
        }

        Long day = diffTime / 60 / 24;
        diffTime = diffTime % (60 * 24);
        if(day > 0) {
            diffDesc = diffDesc + day + "天";
            if(!isFull) {
                return diffDesc + fix;
            }
        }

        Long hour = diffTime / (60);
        diffTime = diffTime % (60);
        if(hour > 0) {
            diffDesc = diffDesc + hour + "时";
            if(!isFull) {
                return diffDesc + fix;
            }
        }

        Long minitue = diffTime ;
        if(minitue > 0) {
            diffDesc = diffDesc + minitue + "分";
            if(!isFull) {
                return diffDesc + fix;
            }
        }

        return diffDesc + fix;
    }

    public static enum TIME_ACCURACY {
        SECOND, MINUTE
    }

    public static String dateToString(String longdate) {

        return dateToString("yyyy-MM-dd",
                new Date(Long.parseLong(longdate)));
    }

    /**时间转化为时间戳,默认格式为yyyy-MM-dd HH:mm:ss
     *
     * @param time
     * @return
     */
    public static String stringTolong1(String time) {

        return stringTolong(time,"yyyy-MM-dd HH:mm:ss");
    }

    /**时间转化为时间戳,默认格式为yyyy-MM-dd
     *
     * @param time
     * @return
     */
    public static String stringTolong(String time) {

        return stringTolong(time,"yyyy-MM-dd");
    }
    /**
     * 时间转化为时间戳
     *
     * @return
     */
    public static String stringTolong(String time, String forDate) {
        if(TextUtils.isEmpty(time) || TextUtils.isEmpty(forDate)){
            return "0";
        }

        SimpleDateFormat sdf = new SimpleDateFormat(forDate);
        Date date = new Date();
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {

            e.printStackTrace();
        }
        return date.getTime() + "";
    }

    /**
     * 字符串转换成日期 yyyy-MM-dd HH:mm:ss
     *
     * @param strFormat
     *            格式定义 如：yyyy-MM-dd HH:mm:ss
     * @param dateValue
     *            日期对象
     * @return
     */
    public static Date stringToDate(String strFormat, String dateValue) {
        if (dateValue == null)
            return null;
        if (strFormat == null)
            strFormat = "yyyy-MM-dd HH:mm";

        SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat);
        Date newDate = null;
        try {
            newDate = dateFormat.parse(dateValue);
        } catch (ParseException e) {
            newDate = null;
            e.printStackTrace();
        }
        return newDate;
    }

    /**
     * 日期转成字符串
     *
     * @param strFormat
     *            格式定义 如：yyyy-MM-dd HH:mm:ss
     * @param date
     *            日期字符串
     * @return
     */
    public static String dateToString(String strFormat, Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat);
        return dateFormat.format(date);
    }

    /**
     * 时间戳转化为时间 : yyyy-MM-dd
     *
     * @param longdate
     * @return
     */
    public static String dateToString(String longdate, String strFormat) {
        if (isNull(longdate) || longdate.length() == 0) {
            return "";
        }
        if (TextUtils.isEmpty(strFormat)) {
            strFormat = "yyyy-MM-dd HH:mm";
        }
        return dateToString(strFormat,
                new Date(Long.parseLong(longdate + "000")));
    }

    /**
     *字符串的日期格式的计算
     * 时间格式
     */
    public static int daysBetween(String smdate,String bdate) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        if(Integer.parseInt(String.valueOf(between_days))<1){
            return 0;
        }else{
            return Integer.parseInt(String.valueOf(between_days));
        }
    }

    /**
     * 计算两个日期间隔天数
     *
     * @param begin
     * @param end
     * @return
     */
    public static int countDays(Date begin, Date end) {
        int days = 0;
        Calendar c_b = Calendar.getInstance();
        Calendar c_e = Calendar.getInstance();
        c_b.setTime(begin);
        c_e.setTime(end);
        while (c_b.before(c_e)) {
            days++;
            c_b.add(Calendar.DAY_OF_YEAR, 1);
        }
        return days;
    }

    /**
     * 计算距离当前日期间隔天数
     *
     * @return
     */
    public static int countDays(Date date) {
        int days = 0;
        Date now = new Date();
        Calendar c_b = Calendar.getInstance();
        Calendar c_e = Calendar.getInstance();
        c_b.setTime(now);
        c_e.setTime(date);
        if (c_b.before(c_e)) {
            while (c_b.before(c_e)) {
                days++;
                c_b.add(Calendar.DAY_OF_YEAR, 1);
            }
        } else {
            while (c_e.before(c_b)) {
                days++;
                c_e.add(Calendar.DAY_OF_YEAR, 1);
            }
        }

        return days;
    }
    /**
     * 获取当前日期，格式：yyyy-MM-dd
     *
     * @return
     */
    public static String getDateNow() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    public static int getCuureaYear(){
        return  getYearByFomatDate(getDateNow());
    }

    /**
     * 获取当前时间，格式：HH:mm:ss
     *
     * @return
     */
    public static String getTimeNow() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(new Date());
    }

    /**
     * 获取年份，格式：yyyy-MM-dd
     *
     * @param date
     * @return
     */
    public static int getYearByFomatDate(String date) {
        if(TextUtils.isEmpty(date)){
            return 1970;
        }
        return Integer.parseInt(date.split("-")[0]);
    }

    /**
     * 获取月份，格式：yyyy-MM-dd
     *
     * @param date
     * @return
     */
    public static int getMonthByFomatDate(String date) {
        return Integer.parseInt(date.split("-")[1]);
    }

    /**
     * 获取日，格式：yyyy-MM-dd
     *
     * @param date
     * @return
     */
    public static int getDayByFomatDate(String date) {
        return Integer.parseInt(date.split("-")[2]);
    }

    /**
     * 是否是日期，格式：yyyy-MM-dd
     *
     * @return
     */
    public static boolean isDate(String strDate) {
        Pattern pattern = Pattern
                .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
        Matcher m = pattern.matcher(strDate);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     */
    public static boolean isDate(String str_input, String rDateFormat) {
        if (!isNull(str_input)) {
            SimpleDateFormat formatter = new SimpleDateFormat(rDateFormat);
            formatter.setLenient(false);
            try {
                formatter.format(formatter.parse(str_input));
            } catch (Exception e) {
                return false;
            }
            return true;
        }
        return false;
    }

    public static boolean isNull(String str) {
        if (str == null)
            return true;
        else
            return false;
    }

    /**
     * date转化为long时间戳
     *
     * @param date
     *            转换时间的date
     * @return
     */
    public static Long Date2Long(Date date) {

        return date.getTime();
    }

    /**
     * 判断当前日期是星期几
     *
     * @param pTime
     *            设置的需要判断的时间 //格式如2012-09-08
     *
     *
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */

    // String pTime = "2012-03-12";
    public static String getWeek(String pTime) {
        String Week = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(format.parse(pTime));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            Week += "星期天";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 2) {
            Week += "星期一";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 3) {
            Week += "星期二";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 4) {
            Week += "星期三";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 5) {
            Week += "星期四";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 6) {
            Week += "星期五";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 7) {
            Week += "星期六";
        }
        return Week;
    }
}
